import styled from 'styled-components'
import Coin from './Coin'
import { useTranslation } from 'react-i18next'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { REFRESH_EARTH_INTERVAL, SECOND_MILL } from '../constants'
import { HomeResponse } from '../service/interface'
import { sigFigs } from '../utils/number'
import NewCoin from './NewCoin'

const Container = styled.div<{ $isNew?: number }>`
    position: relative;
    padding-top: ${({ $isNew }) => $isNew ? '1rem' : '2.5rem'};
    box-sizing: border-box;
    z-index: 99;
    font-weight: bold;
`

const CoinBox = styled.div`
    display: flex;
    padding: 0 1rem;
    justify-content: space-between;
    width: 100%;
    box-sizing: border-box;
`

type IntervalType = { interval: number, count: number };
interface Props {
    isNew?: boolean, //是否是新的样式
    btcCount: number,
    countPerInterval?: number,
    inteval?: number,
    stopTime?: number;
    data?: HomeResponse,
    dynamicInterval?: Array<IntervalType>, // if dynamicInterval is not null, will use it first. After all time is done, will use inteval and countPerInterval
    onStop?: () => void,
}

const Header: React.FC<{ count: number, isNew?: boolean }> = ({ count, isNew }) => {
    const { t } = useTranslation();
    const balance = useMemo(() => sigFigs((count < 0 ? 0 : count).toFixed(3)), [count])
    return <Container $isNew={Number(isNew)}>
        <CoinBox>
            {isNew ? <NewCoin
                icon="icon_coin"
                subTitle={balance}
                title={t('home.coin')}
            /> : <Coin
                icon="icon_coin"
                subTitle={balance}
                title={t('home.coin')}
            />}
        </CoinBox>
    </Container>
}

const HeaderCounter: React.FC<Props> = ({ btcCount, countPerInterval, dynamicInterval, isNew = false, stopTime = 0, inteval = REFRESH_EARTH_INTERVAL, onStop }) => {
    const [count, setCount] = useState(btcCount)

    const updateData = useCallback((realInteval: number, increase: number, time: number, type: 'timeout' | 'interval', onFinish?: (leftTime: number) => void) => {
        const second = realInteval / SECOND_MILL
        const func = type === 'timeout' ? setTimeout : setInterval;
        let leftTime = time;
        const timer = func(() => {
            setCount(pre => pre + increase)
            leftTime = leftTime - second
            if (leftTime <= 0) {
                leftTime = 0;
                onStop?.();
            }
            onFinish?.(leftTime);
        }, realInteval);
        return timer
    }, [onStop])

    const repeat = useCallback((list: Array<IntervalType>, idx: number, time: number, intervalTime: number, increaseCount: number) => {
        const item = list[idx];
        let type: any = 'timeout'
        let realInterval = item?.interval;
        let increase = item?.count;
        if (!item) {
            type = 'interval'
            realInterval = intervalTime
            increase = increaseCount
        }

        if (realInterval <= 0 || increase <= 0 || time <= 0) {
            return;
        }

        const timer = updateData(realInterval, increase, time, type, (leftTime: number) => {
            if (type === 'timeout') {
                clearTimeout(timer)
                repeat(list, idx + 1, leftTime, intervalTime, increaseCount)
            }
        })
        return timer;
    }, [updateData])

    useEffect(() => {
        setCount(btcCount);
        if (stopTime <= 0 || (!countPerInterval && !dynamicInterval?.length)) {
            return
        }

        const timer = repeat(dynamicInterval || [], 0, stopTime, inteval, countPerInterval || 0)
        return () => {
            if (timer) {
                clearTimeout(timer)
                clearInterval(timer)
            }
        }
    }, [btcCount, countPerInterval, stopTime, onStop, inteval, dynamicInterval, repeat])
    return <Header
        count={count}
        isNew={isNew}
    />
}

const HeaderComponent: React.FC<Props> = (prop) => {
    return prop.countPerInterval ? <HeaderCounter {...prop} /> : <Header
        count={prop.btcCount}
        isNew={prop.isNew}
    />
}

export default HeaderComponent